package org.example.dao;

import org.example.model.User;
import org.example.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {

    //根据账号查询用户信息
    public static User queryByUsername(String username) {
        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            //1.获取数据库连接
            c = DBUtil.getConnection();
            String sql = "select * from user where username=?";
            //2.创建操作命令对象
            ps = c.prepareStatement(sql);
            //替换占位符: 第一个参数是占位符的索引（从1开始）
            ps.setString(1, username);
            //3.执行sql：查询是executeQuery方法，返回结果集
            rs = ps.executeQuery();
            //4.处理结果集
            while(rs.next()){
                User user = new User();
                //转换一行数据为一个用户对象，返回
                user.setId(rs.getInt("id"));
                user.setUsername(username);//结果集账号和传入的是一样的
                user.setPassword(rs.getString("password"));
                return user;
            }
            return null;
        }catch (Exception e){
            throw new RuntimeException("根据账号查询用户出错", e);
        }finally {
            DBUtil.close(c, ps, rs);
        }
    }

    public static User registerHasUser(String username) {
        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            c = DBUtil.getConnection();
            String sql = "select * from user where username=?";
            //2.创建操作命令对象
            ps = c.prepareStatement(sql);
            //替换占位符: 第一个参数是占位符的索引（从1开始）
            ps.setString(1, username);
            rs = ps.executeQuery();
            while(rs.next()){
                User user = new User();
                user.setUsername(username);
                return user;
            }
            return null;
        }catch (Exception e) {
            throw new RuntimeException("注册失败", e);
        }finally {
            DBUtil.close(c,ps);
        }
    }

    public static int registerNewUser(User user) {
        Connection c = null;
        PreparedStatement ps = null;
        try{
            c = DBUtil.getConnection();
            String sql = "insert into user(username, password) values(?,?)";
            //2.创建操作命令对象
            ps = c.prepareStatement(sql);
            //替换占位符: 第一个参数是占位符的索引（从1开始）
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            return ps.executeUpdate();
        }catch (Exception e) {
            throw new RuntimeException("注册失败", e);
        }finally {
            DBUtil.close(c,ps);
        }
    }


}
